﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Collections;

namespace FreeFlow.Administration
{
  /// <summary>
  /// A collection of Windows Workflow instances
  /// </summary>
  public sealed class WorkflowInstanceCollection : DatabaseAware, IEnumerable<WorkflowInstance>, IList, IRefreshable
  {
    /// <summary>
    /// Initializes a new instance of the <see cref="WorkflowInstanceCollection"/> class.
    /// </summary>
    /// <param name="server">The server.</param>
    public WorkflowInstanceCollection(Server server)
      : base(server)
    {

    }

    private List<WorkflowInstance> instances;
    /// <summary>
    /// Gets the number of Windows Workflow instances in this collection.
    /// </summary>
    public int Count
    {
      get
      {
        ReadInstances();
        return instances.Count;
      }
    }

    private void ReadInstances()
    {
      if (instances == null)
      {
        instances = new List<WorkflowInstance>();
        using (IDataReader reader = Server.ExecuteReader("SELECT DISTINCT eWorkflowInstance, eFolderID, " +  
          "(SELECT MIN(eEventDateTime) FROM eMSWorkflowTracking WHERE eWorkflowInstance=T.eWorkflowInstance) AS CreatedTime " +
          "FROM eMSWorkflowTracking T ORDER BY CreatedTime"))
        {
          while (reader.Read())
          {
            WorkflowInstance instance = new WorkflowInstance(Server, reader);
            instances.Add(instance);
          }
        }
      }
    }

    #region IEnumerable<WorkflowInstance> Members

    /// <summary>
    /// Returns an enumerator that iterates through the collection.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
    /// </returns>
    public IEnumerator<WorkflowInstance> GetEnumerator()
    {
      ReadInstances();
      return instances.GetEnumerator();
    }

    #endregion

    #region IEnumerable Members

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
      ReadInstances();
      return instances.GetEnumerator();
    }

    #endregion

    #region IList Members

    int IList.Add(object value)
    {
      throw new NotImplementedException();
    }

    void IList.Clear()
    {
      throw new NotImplementedException();
    }

    bool IList.Contains(object value)
    {
      throw new NotImplementedException();
    }

    int IList.IndexOf(object value)
    {
      throw new NotImplementedException();
    }

    void IList.Insert(int index, object value)
    {
      throw new NotImplementedException();
    }

    bool IList.IsFixedSize
    {
      get { throw new NotImplementedException(); }
    }

    bool IList.IsReadOnly
    {
      get 
      {
        return true;
      }
    }

    void IList.Remove(object item)
    {
      Remove((WorkflowInstance)item);
    }

    /// <summary>
    /// Removes the specified workflow instance from the collection and the database.
    /// </summary>
    /// <param name="workflowInstance">The workflow instance to remove.</param>
    public void Remove(WorkflowInstance workflowInstance)
    {
      ReadInstances();
      if (instances.Contains(workflowInstance))
      {
        workflowInstance.Delete();
        instances.Remove(workflowInstance);
      }
    }

    /// <summary>
    /// Removes the <see cref="T:System.Collections.IList"/> item at the specified index.
    /// </summary>
    /// <param name="index">The zero-based index of the item to remove.</param>
    /// <exception cref="T:System.ArgumentOutOfRangeException">
    /// 	<paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.IList"/>.
    /// </exception>
    /// <exception cref="T:System.NotSupportedException">
    /// The <see cref="T:System.Collections.IList"/> is read-only.
    /// -or-
    /// The <see cref="T:System.Collections.IList"/> has a fixed size.
    /// </exception>
    public void RemoveAt(int index)
    {
      ReadInstances();
      WorkflowInstance version = instances[index];
      Remove(version);
    }

    object IList.this[int index]
    {
      get
      {
        ReadInstances();
        return instances[index];
      }
      set
      {
        throw new NotImplementedException();
      }
    }

    #endregion

    #region ICollection Members

    /// <summary>
    /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
    /// </summary>
    /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
    /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
    /// <exception cref="T:System.ArgumentNullException">
    /// 	<paramref name="array"/> is null.
    /// </exception>
    /// <exception cref="T:System.ArgumentOutOfRangeException">
    /// 	<paramref name="index"/> is less than zero.
    /// </exception>
    /// <exception cref="T:System.ArgumentException">
    /// 	<paramref name="array"/> is multidimensional.
    /// -or-
    /// <paramref name="index"/> is equal to or greater than the length of <paramref name="array"/>.
    /// -or-
    /// The number of elements in the source <see cref="T:System.Collections.ICollection"/> is greater than the available space from <paramref name="index"/> to the end of the destination <paramref name="array"/>.
    /// </exception>
    /// <exception cref="T:System.ArgumentException">
    /// The type of the source <see cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.
    /// </exception>
    public void CopyTo(WorkflowInstance[] array, int index)
    {
      ReadInstances();
      instances.CopyTo(array, index);
    }

    void ICollection.CopyTo(Array array, int index)
    {
      CopyTo((WorkflowInstance[])array, index);
    }

    int ICollection.Count
    {
      get 
      {
        ReadInstances();
        return instances.Count;
      }
    }

    bool ICollection.IsSynchronized
    {
      get { throw new NotImplementedException(); }
    }

    object ICollection.SyncRoot
    {
      get { throw new NotImplementedException(); }
    }

    #endregion

    #region IRefreshable Members

    /// <summary>
    /// Refreshes the collection.
    /// </summary>
    public void Refresh()
    {
      instances = null;
    }

    #endregion
  }
}
